#!/bin/bash

if [ $# -eq 0 ]; then
    echo "Usage: $0 <port>"
    echo "Example: $0 8080"
    exit 1
fi

PORT=$1

if ! [[ "$PORT" =~ ^[0-9]+$ ]] || [ "$PORT" -lt 1 ] || [ "$PORT" -gt 65535 ]; then
    echo "Error: Port must be a number between 1 and 65535"
    exit 1
fi

echo "Searching for processes using port $PORT..."

PIDS=$(lsof -ti:$PORT 2>/dev/null)

if [ -z "$PIDS" ]; then
    echo "No processes found using port $PORT"
    exit 0
fi

echo "Found processes using port $PORT:"
lsof -i:$PORT

echo ""
read -p "Kill these processes? (y/N): " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Killing processes..."
    for PID in $PIDS; do
        if kill -9 $PID 2>/dev/null; then
            echo "Killed process $PID"
        else
            echo "Failed to kill process $PID (may have already exited)"
        fi
    done
    echo "Done."
else
    echo "Cancelled."
fi